package com.sogoodsoft.service.crm;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sogoodsoft.dao.common.CommonHibernateDao;
import com.sogoodsoft.dao.crm.CustomerDao;
import com.sogoodsoft.dao.crm.OrderDetailDao;
import com.sogoodsoft.dao.crm.OrderFormDao;
import com.sogoodsoft.entity.app.SysClass;
import com.sogoodsoft.entity.crm.Customer;
import com.sogoodsoft.entity.crm.OrderDetail;
import com.sogoodsoft.entity.crm.OrderForm;
import com.sogoodsoft.service.app.SysClassService;
import com.sogoodsoft.service.common.AbstractService;

@Component
@Transactional
public class OrderService extends AbstractService<OrderForm, Long> {

	@Autowired
	private OrderFormDao dao;

	@Autowired
	private OrderDetailDao detailDao;

	@Autowired
	private SysClassService sysSer;

	@Autowired
	private CustomerDao customerDao;

	private final static String orderedCustomerTypeCode = "CUSTOMER_TYPE_DDKH";


	@Override
	public CommonHibernateDao<OrderForm, Long> getDao() {
		return dao;
	}

	public void save(OrderForm t, List<OrderDetail> detail) {

		// 订单明细
		List<OrderDetail> list = t.getDetail();

		// 修改时，删除原有订单,生成新订单
		if (t.getId() != null) {
			for (OrderDetail order : list) {
				detailDao.delete(order);
			}
			t.setDetail(null);
			dao.save(t);
		}
		for (OrderDetail order : detail) {
			String str = "goodsid=" + order.getGoodsid();
			str += " model=" + order.getGoodsmodel();
			str += " unit=" + order.getGoodsunit();
			str += " price=" + order.getGoodsprice();
			str += " count=" + order.getGoodscount();
			str += " id=" + order.getId();
			// logger.debug(str);
			order.setOrder(t);
			detailDao.save(order);
		}
		dao.save(t);
	}

	public long getOrderCode() {
		return Long.parseLong(OrderSerialService.getSerial());
	}

	public OrderForm getByCode(String code) {
		return dao.findUnique("from OrderForm where code=?", code);
	}

	/**
	 * 订单确订，保存确认人，确认时间 更新客户资料，把潜在客户状态，改为订单客户
	 * 
	 * @param entity
	 */
	public void confirm(OrderForm entity) {
		dao.save(entity);

		// 更新客户类型
		if (entity.getCustomerid() != null) {
			Customer customer = customerDao.get(entity.getCustomerid());
			if (!orderedCustomerTypeCode.equals(customer.getType().getCode())) {
				SysClass type = sysSer.getByCode(orderedCustomerTypeCode);
				customer.setType(type);
				customerDao.save(customer);
			}

		}
	}
}
